﻿#region License

// Another free, open solution by someone who gets it.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using Patterns.SafeCode;

namespace Patterns.Collections
{
	/// <summary>
	/// 	Defines extensions for the generic and non-generic enumerable types.
	/// </summary>
	public static class EnumerableExtensions
	{
		/// <summary>
		/// 	Runs the specified action against each item in the set.
		/// </summary>
		/// <typeparam name = "T">The item type.</typeparam>
		/// <param name = "items">The items.</param>
		/// <param name = "action">The action.</param>
		/// <param name = "parallel">If set to <c>true</c>, run the action across the set in parallel.
		/// 	The default is <c>false</c>.</param>
		/// <param name = "errorHandler">The error handler (optional).</param>
		/// <remarks>
		/// 	If the <paramref name = "parallel" /> parameter is set to <c>true</c>, the
		/// 	<see cref = "Parallel" /> class is used to execute asynchronous <see cref = "Task" /> objects
		/// 	agsinst the set. See <see cref = "System.Threading.Tasks" /> for details.
		/// 	<br />
		/// 	Error handling is provided by <see cref = "Try.HandleErrors.DefaultStrategy" />
		/// 	if no error handler is specified.
		/// </remarks>
		/// <seealso cref = "Try" />
		public static void Each<T>(this IEnumerable<T> items, Action<T> action, bool parallel = false, Action<Exception> errorHandler = null)
		{
			if (parallel) Parallel.ForEach(items, item => Try.Do(() => action(item), errorHandler));
			else
			{
				foreach (T item in items)
				{
					T currentItem = item;
					Try.Do(() => action(currentItem), errorHandler);
				}
			}
		}
	}
}